package restaurant.behaviours.master;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.ListIterator;

import restaurant.agents.MasterWaiterAgent;
import restaurant.core.CustomizedPerformative;
import restaurant.core.Request;

public class MasterBillChoiceBehaviour extends CyclicBehaviour {
	
	private static final long serialVersionUID = -1778376869387705824L;
	private MasterWaiterAgent agent;
	
	public MasterBillChoiceBehaviour(MasterWaiterAgent agent) {
		this.agent = agent;
	}

	@Override
	public void action() {
		if(this.agent.restaurant.bills.isEmpty())
			return;
		
		if(this.agent.freeWaiters.size() == 0)
			return;
		
		synchronized (this.agent.restaurant.bills) {
			ListIterator<Hashtable<Request, Boolean>> iterator = this.agent.restaurant.bills.listIterator();
			while(iterator.hasNext()) {
				Hashtable<Request, Boolean> hashtable = iterator.next();
				Request r = hashtable.keys().nextElement();
				if(!hashtable.get(r)) {
					for (Iterator<AID> waiter = this.agent.freeWaiters.keySet().iterator(); waiter.hasNext();) {
						AID tmp = waiter.next();
						if (this.agent.freeWaiters.get(tmp)) {
							this.agent.setScore(this.agent.getScore() + (1000/(System.currentTimeMillis() + 1 - this.agent.calledTime.get(r.getTable()))));
							
							hashtable.put(r, true);
							this.agent.freeWaiters.put(tmp, false);
							ACLMessage message = new ACLMessage(CustomizedPerformative.AVAILABLE_WAITER);
							message.setContent("" + CustomizedPerformative.BILL);
							message.addReceiver(tmp);

							System.out.println("MasterWaiterAgent: Vai al tavolo per il conto");

							myAgent.send(message);
							return;
						}
					}
				}
			}
		}

//		for(Hashtable<Request, Boolean> hash : this.agent.restaurant.bills) {
//			Request r = hash.keys().nextElement();
//			if(!hash.get(r)) {
//				for (Iterator<AID> waiter = this.agent.freeWaiters.keySet().iterator(); waiter.hasNext();) {
//					AID tmp = waiter.next();
//					if (this.agent.freeWaiters.get(tmp)) {
//						this.agent.setScore(this.agent.getScore() + (1000/(System.currentTimeMillis() + 1 - this.agent.calledTime.get(r.getTable()))));
//						
//						hash.put(r, true);
//						this.agent.freeWaiters.put(tmp, false);
//						ACLMessage message = new ACLMessage(CustomizedPerformative.AVAILABLE_WAITER);
//						message.setContent("" + CustomizedPerformative.BILL);
//						message.addReceiver(tmp);
//
//						System.out.println("MasterWaiterAgent: Vai al tavolo per il conto");
//
//						myAgent.send(message);
//						return;
//					}
//				}
//			}
//		}
	}

}